package org.biubiu0002.baiblog.core.async.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.common.constants.ShareConstants;
import org.biubiu0002.baiblog.core.async.event.UpdateShareEvent;
import org.biubiu0002.baiblog.core.config.RabbitMqConfig;
import org.biubiu0002.baiblog.core.model.vo.res.ShareInfoVo;
import org.biubiu0002.baiblog.core.service.ShareService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-31 22:56
 **/
@RabbitListener(queues = RabbitMqConfig.UPDATE_SHARE_QUEUE)
@Component
@Slf4j
public class UpdateShareListener {

    @Resource
    private ShareService shareService;

    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(msg));
            log.info("收到更改推文消息: {}", msg);
            UpdateShareEvent updateShareEvent = JSON.parseObject(msg, UpdateShareEvent.class);
            ShareInfoVo oldShareInfoVo = updateShareEvent.getOldShareInfoVo();
            ShareInfoVo newShareInfoVo = updateShareEvent.getNewShareInfoVo();
            String shareId = newShareInfoVo.getShareId();
            if (newShareInfoVo.getSharePostStatus() == ShareConstants.SharePostStatusEnum.NO_VIEW.getCode()) {
                //从榜单中移除
                shareService.removeFromLikeCountBoard(shareId);
                shareService.removeFromLatestBoard(shareId);
            }
            // 从榜单中恢复
            if (oldShareInfoVo.getSharePostStatus()== ShareConstants.SharePostStatusEnum.NO_VIEW.getCode() &&
                    newShareInfoVo.getSharePostStatus()!= ShareConstants.SharePostStatusEnum.NO_VIEW.getCode()){
                shareService.recoverFromLikeCountBoard(shareId);
                shareService.recoverFromLatestBoard(shareId);
            }
            // 其他情况 已经删除了boardItemVo的key了 在查询的时候可以查出新值
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            if (Boolean.TRUE.equals(message.getMessageProperties().isRedelivered())) {
                log.error("[消费拒绝]:{}",message,e);
                channel.basicReject(deliveryTag, false);
            } else {
                log.warn("[消费重试]:{}",message,e);
                channel.basicNack(deliveryTag, false, true);
            }
        }


    }
}
